package com.hp.itsm.api.examples;

import java.io.File;
import com.hp.itsm.api.*;
import com.hp.itsm.api.interfaces.*;

/**
 * This example shows how an attachment can be added to an item.
 * It opens a session using the server name, user name and the password.
 * Next it opens an item using the item type and the item id and it tries
 * to attach the file to item.
 */
public class Example9
{
    /**
     * Arguments
     *   server    : The server to connect to.
     *               Format: <ip_addresss|computer_name>[:<port>]
     *                  e.g.  192.168.1.13
     *                        192.168.1.13:30999
     *                        some.machine.hp.com
     *                        some.machine.hp.com:30999
     *   username  : The username of the account you want to use.
     *               It must be a known service desk user that is
     *               allowed to log on.
     *   password  : The password of the account you want to use.
     *   item      : The item type, e.g. Servicecall, ConfigurationItem
     *   id        : The functional id of the item
     *   file      : The file name.
     *               The server has to have access rights to this file
     */
    public static void main(String args[]) {
        if (args.length != 6) {
            System.err.println("Usage : "
                + "Example9 <server> <username> <password> <item> <id> <file>");
            System.err.println("<item>: "
                + "ConfigurationItem, Incident, Servicecall, Problem, Change, Person");
            return;
        }

        String server   = args[0];
        String username = args[1];
        String password = args[2];
        String itemType = args[3];
        long   id       = Long.valueOf(args[4]).longValue();
        String fileName = args[5];

       /*
        * Open a session to a running Service Desk application Server.
        * Once you have a connection, you can use it to communicate with
        * the server. The connection has an instance of the workflow layer
        * on the server that keeps the state information of this client.
        */
        ApiSDSession session = null;
        try {
            session = ApiSDSession.openSession(server, username, password);
        } catch (RuntimeException e) {
           /*
            * Connecting can go wrong for various reasons. E.G. No server
            * is running on this particular computer/port combination or
            * the user/password combination is wrong. Catch the exception
            * and print an error message for the user or for the log. The
            * Web-API makes an effort to give sensible messages in the
            * exceptions, and if possible, the messages are localised.
            *
            * Note: in some applications System.out.println() does not work.
            */
            System.out.println(e.getMessage());
            return;
        }

        // Decide on the item type and open the item with the passed id
        ILifeCycleObject item = null;
        try {
            if (itemType.equalsIgnoreCase("ConfigurationItem")) {
                IConfigurationItemHome ciHome = session.getConfigurationItemHome();
                item = ciHome.openConfigurationItem(id);
            } else if (itemType.equalsIgnoreCase("Incident")) {
                IIncidentHome incHome = session.getIncidentHome();
                item = incHome.openIncident(id);
            } else if (itemType.equalsIgnoreCase("Servicecall")) {
                IServicecallHome scHome = session.getServicecallHome();
                item = scHome.openServicecall(id);
            } else if (itemType.equalsIgnoreCase("Problem")) {
                IProblemHome pbHome = session.getProblemHome();
                item = pbHome.openProblem(id);
            } else if (itemType.equalsIgnoreCase("Change")) {
                IChangeHome chHome = session.getChangeHome();
                item = chHome.openChange(id);
            } else if (itemType.equalsIgnoreCase("Person")) {
                IPersonHome pHome = session.getPersonHome();
                item = pHome.openPerson(new Long(id));
            } else {
                System.out.println("Unknown item type: " + itemType);
                return;
            }
        } catch (RuntimeException e) {
            System.out.println("Exception for itemType = "
                + itemType + " and id = " + id);
            System.out.println(e.getMessage());
            return;
        }

        // Show the existing attachments
        System.out.println("\nInitial attachments of " + itemType + " " + id);
        IAttachment att = item.getAttachment();
        printAttachmentInfo(att);

        // Build a new attached item
        IAttachedItemHome aHome = session.getAttachedItemHome();
        IAttachedItem nItem = aHome.openNewAttachedItem();
        File f = new File(fileName);
        nItem.setFilename(fileName);
        nItem.setBaseName(f.getName());
        // Make the new attached item aware of its parent entity type. This
        // attribute is not automatically set when the new attached item is
        // added to a parent.
        IEntityInfoHome entInfHome = session.getEntityInfoHome();
        IEntityInfo entInfo = entInfHome.openEntityInfo(item.getItemType());
        nItem.setParentEntityType(entInfo);

        // Add the new attached item, it is automatically saved
        att.addAttachedItem(nItem);

        // The boolean AttachmentExists of the parent is not automatically
        // updated. So it should be updated when it is still false.
        try {
            if (!att.getAttachmentExists().booleanValue()) {
                att.setAttachmentExists(new Boolean(true));
                att.transfer();
                item.save();
            }
        } catch (RuntimeException e) {
           System.out.println("Boolean AttachmentExists has not been updated!");
           System.out.println(e.getMessage());
           return;
        }

        //Show the existing attachments
        System.out.println("\nCurrent attachments of " + itemType + " " + id);
        printAttachmentInfo(att);
        return;
    }

    public static void printAttachmentInfo(IAttachment attachment) {
        if (attachment != null) {
            boolean exists = attachment.getAttachmentExists().booleanValue();
            IAttachedItem[] aItems = attachment.getAttachedItems();
            int length = aItems.length;

            System.out.println("AttachmentExists: " + exists);
            System.out.println("Attached Items: ");
            for (int i = 0; i < length; i++) {
                System.out.println( "\t" + i
                                  + "\t" + aItems[i].getBaseName()
                                  + "\t" + aItems[i].getFilename()
                                  );
            }
            if ((exists && length < 1) || (!exists && length > 0)) {
                System.out.println("Warning: Discrepancy");
                System.out.println("         between number of attachments");
                System.out.println("         and boolean AttachmentExists");
            }
        }
    }

    public static final String REVISION = "$Revision: 3 $";
}

